package com.myacg.core.dao.service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.myacg.core.dao.entity.Record;
import com.myacg.core.dao.utils.JsonFileUtil;


/**
 * ����json�ļ��ĳ�������
 * �ṩ��������ɾ�Ĳ鷽������ 
 * �����ڼ̳�record�Ķ��� (record���������id ��createtime����)
 * @author Administrator
 *
 */
public class RecordService<T extends Record> {
	private String basePath;
	private String indexfilePath;
	Class<T> entityClass = null;
	
	
	public RecordService(Class<T> entityClass,String baseDir){
		this(entityClass,baseDir, "index.bak");
	}
	public RecordService(Class<T> entityClass,String baseDir,String fileName){
		this.basePath=baseDir;
		if(this.basePath!=null)
		this.indexfilePath=basePath+fileName;
		this.entityClass = entityClass;
		this.init();
		System.out.println("[RecordService] Load : "+this.entityClass.getName() +" From : "+this.indexfilePath);
	}
	 
	
	/**
	 * ��ʼ��·���µ��ļ�
	 */
	private  void init(){
		
		if(this.indexfilePath!=null){
		   File dir =new File(basePath);
		   File file =new File(indexfilePath);
		   if(!file.exists()){
		    try {
		    	 System.err.println("created file sucess:"+indexfilePath);
				 dir.mkdirs();
				 file.createNewFile();
			} catch (IOException e) {
				System.err.println(this.indexfilePath+"  create err  : "+e.getMessage());
			}
		   }
			
		}
	}
	/**
	 * ��ȡ��������
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<T>  getAllRecords(){
		return  JsonFileUtil.readListFromFile(entityClass, this.indexfilePath);
	}
	 
	/**
	 * ��ȡid��Ӧ��
	 * @param id
	 * @return
	 */
	public T getOne(List<T> records,final String id){
		List<T> records2=this.filterList(records, new ListFilter<T>() {
						public boolean filter(T obj) {
							//ɸѡ�����������
							return obj.getId().equals(id);
						}
					 });
		return records2.size()>0 ? records2.get(0) : null;
	}
	 
	/**
	 * ����ĳ��
	 * @param record
	 * @return
	 */
	public boolean updateRecord(T record){
		if(record!=null){
			List<T>  records=this.getAllRecords();
			if(record.getId()!= null){
				 T oldrec = this.getOne(records, record.getId());
				 if(oldrec!=null){
					 records.remove(oldrec);
				 } 
				  records.add(record);
				  
			}else{
				//����һ���µ�id�Ų�
				String newid=this.getNewId(records);
				record.setId(newid);
				records.add(record);
			}
			//�洢
			return JsonFileUtil.saveListToFile(records, this.indexfilePath);
		} 
			return false;
	}
	
	/**
	 * ����ĳ��
	 * @param record
	 * @return
	 */
	public boolean addRecords(List<T> records){
			List<T> saverecords  = this.getAllRecords(); //获取原始的
			//存储新值
			for (T record : records) {
				record.setId(this.getUUID());
				record.setCreateTime(new Date().getTime());
				saverecords.add(record);
			}
			return JsonFileUtil.saveListToFile(saverecords, this.indexfilePath);
	}
	/**
	 * ����ĳ��
	 * @param record
	 * @return
	 */
	public boolean addRecord(T record){
			List<T> saverecords  = this.getAllRecords(); //获取原始的
			record.setId(this.getUUID());
			record.setCreateTime(new Date().getTime());
			saverecords.add(record);
			return JsonFileUtil.saveListToFile(saverecords, this.indexfilePath);
	}
	
	/**
	 * ɾ��id��Ӧ�ļ�¼
	 * @param id
	 * @return
	 */
	public boolean  deletedOne(String id){
		if(id!=null){
			List<T>  records=this.getAllRecords();
			//�������Ƴ�
			records.remove(this.getOne(records, id));
			//����ɾ��
			return JsonFileUtil.saveListToFile(records, this.indexfilePath);
		}
		return false;
	}
	
	
	/**
	 * ɾ��id��Ӧ�ļ�¼
	 * @param id
	 * @return
	 */
	public boolean  deletedAll(){
			List<T>  records= new ArrayList<>();
			return JsonFileUtil.saveListToFile(records, this.indexfilePath);
	}
	
	/**
	 * ���ݶ���������id�Ż�ȡһ�����µ�id
	 * @param allRecords
	 * @return
	 */
	public  String getNewId(List<? extends Record> allRecords){
		//����id����
		if(allRecords.size()>0){
			Record[] desc = new Record[allRecords.size()] ;
			desc=allRecords.toArray(desc);
			Arrays.sort(desc,new Comparator<Record>() {
				public int compare(Record o1,Record o2) {
					return o1.getId().compareTo(o2.getId());
				}
			});
		 
		   return String.valueOf((Long.parseLong(desc[desc.length-1].getId())+1));	
		}
		return "1";
	}
	
	/**
	 * ��ȡ����ʱ���һ����¼
	 * @param allrecords
	 * @return
	 */
	public T getLastByTime(List<? extends Record>  allrecords){
		if(allrecords==null || allrecords.size()<=0){
			return null;
		}
		Record[] desc = new Record[allrecords.size()] ;
		desc=allrecords.toArray(desc);
		
		Arrays.sort(desc,new Comparator<Record>() {
			public int compare(Record o1,Record o2) {
				return -Long.compare(o1.getCreateTime(), o2.getCreateTime());
			}
		});
		
		/*  allrecords.sort(new Comparator<T>() {
			public int compare(T arg0, T arg1) {
				// TODO Auto-generated method stub
				return -Long.compare(arg0.getCreateTime(), arg1.getCreateTime());
			}
		});*/
	  return (T) desc[0];//���һλ
	}
	
	
	
	
	/**
	 * ����fileFileter��ȡĳЩ���������Ľ��
	 * @param records
	 * @param fileFilter
	 * @return
	 */
	public List<T> filterList(List<T> records,ListFilter<T> fileFilter){
		 List<T>  res=new ArrayList<>();
		 if(records!=null && records.size()>0)
		 for (T record : records) {
			 if(fileFilter.filter(record)){
				 res.add(record);
			 }
		 }
		 return res;
	}
	/**
	 * 生成唯一标识符的id
	 * @return
	 */
	public   String getUUID(){
		return UUID.randomUUID().toString().replace("-", "");
	} 
}
